package cn.tedu.csmall.passport.controller;

import cn.tedu.csmall.passport.ex.ServiceException;
import cn.tedu.csmall.passport.pojo.dto.AdminAddNewDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminInformationDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminLoginInfoDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminUpdatePasswordDTO;
import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.passport.security.LoginPrincipal;
import cn.tedu.csmall.passport.service.IAdminService;
import cn.tedu.csmall.passport.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admins")
@Api(tags = "01.管理员管理模块")
public class AdminController {
    @Autowired
    private IAdminService service;

    @PostMapping("/add-new")
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult<Void> addNew(@Valid AdminAddNewDTO adminAddNewDTO) {
        service.addNew(adminAddNewDTO);
        return JsonResult.OK();
    }

    @ApiOperation("删除管理员")
    @PostMapping(value = "/{id:[0-9]+}/delete")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "管理员id", dataType = "long", required = true)
    )
    public JsonResult<Void> delete(@PathVariable Long id, @ApiIgnore HttpSession httpSession) {
        log.debug("即将处理【删除品牌】的请求,id={}", id);
        try {
            service.deleteById(id);
            return JsonResult.OK();
        } catch (ServiceException e) {
            return JsonResult.fail(e);
        }
    }
    @ApiOperation("启动品牌")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParam(name = "id",value = "是否启用,1=启用,0=禁止",example = "1",required = true)
    @PostMapping("/{id:[a-zA-Z]+}/enable")
    public String setEnable(@PathVariable Long id,@ApiIgnore HttpSession httpSession){
        log.debug("处理请求,id={}",id);
        try {
            service.setEnable(id);
            return "已经处理";
        } catch (ServiceException e) {
            return e.getMessage()+"["+e.getCode()+"]";
        }
    }
    @ApiOperation("禁用品牌")
    @ApiOperationSupport(order = 301)
    @PostMapping("/disable")
    public String setDisable(Long id) {
        log.debug("处理请求,id={}" , id);
        try {
            service.setDisable(id);
            return "已经处理";
        } catch (ServiceException e) {
            return e.getMessage() + "[" + e.getCode() + "]";
        }
    }
    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 88)
    @PostMapping("/login")
    public JsonResult<String> login(AdminLoginInfoDTO adminLoginInfoDTO) {
        log.debug("开始处理【登录认证】的请求，参数：{}", adminLoginInfoDTO);
        String jwt = service.login(adminLoginInfoDTO);
        log.debug("即将向客户端响应JWT数据：{}", jwt);
        return JsonResult.OK(jwt);
    }

    @ApiOperation("修改密码")
    @PostMapping("/updateById")
    public JsonResult<Void> updateById(Long id, AdminUpdatePasswordDTO adminUpdatePasswordDTO){
        service.updatePasswordById(id,adminUpdatePasswordDTO);
        return JsonResult.OK();
    }
    @ApiOperation("修改用户基本信息")
    @PostMapping("/updateInfoById")
    public JsonResult<Void> updateInfoById(Long id,AdminInformationDTO adminInformationDTO){
        service.updateInfoById(id,adminInformationDTO);
        return JsonResult.OK();
    }
    // http://localhost:9081/admins
    @ApiOperation(value = "查询管理员列表", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 400)
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    @GetMapping("")
    public JsonResult<List<AdminListItemVO>> list(
            @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【查询管理员列表】的请求……");
        log.debug("从SecurityContext中获取到的当事人（当前JWT表示的用户）的id：{}", loginPrincipal.getId());
        log.debug("从SecurityContext中获取到的当事人（当前JWT表示的用户）的用户名：{}", loginPrincipal.getUsername());
        List<AdminListItemVO> list = service.list();
        return JsonResult.OK(list);
    }
}
